package com.infinit.easyreader.ui;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.infinit.easyreader.R;
import com.infinit.easyreader.adpter.BookmarkPagerAdapter;
import com.infinit.easyreader.entity.Book;
import com.infinit.easyreader.fragment.BookmarkFragment;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class BookmarkList extends AppCompatActivity {

    public static final String BOOK_ID = "bookId";
    public static final String BOOK_LENGTH = "bookLength";
    @Bind(R.id.ibBookmarkBack)
    ImageButton ibBookmarkBack;
    @Bind(R.id.tabBookmark)
    TabLayout tabBookmark;
    @Bind(R.id.tvBookName)
    TextView tvBookName;
    @Bind(R.id.markPager)
    ViewPager markPager;
    private Book curBook;
    private List<Fragment> fragmentList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bookmark_list);
        ButterKnife.bind(this);
        curBook = getIntent().getParcelableExtra(ReaderActivity.INTENT_BOOK);
        int bookLength = getBookLength();
        //设置上方Topbar的标题
        String bookName = curBook.getName();
        //获取不带后缀名的文件名
        bookName = bookName.substring(0, bookName.lastIndexOf("."));
        tvBookName.setText(bookName);
        //设置数据源
        fragmentList = new ArrayList<>();
        BookmarkFragment markFragment = new BookmarkFragment();
        //向fragment传输数据
        Bundle bundle = new Bundle();
        bundle.putInt(BOOK_ID, curBook.getBookId());
        bundle.putInt(BOOK_LENGTH, bookLength);
        markFragment.setArguments(bundle);
        Fragment phFragment = new Fragment();
        fragmentList.add(markFragment);
        fragmentList.add(phFragment);


        //设置适配器
        setAdapter();
        tabBookmark.setupWithViewPager(markPager);
        //设置监听器
        setListener();

    }

    /**
     * 作用：获取当前的书籍的大小
     */

    private int getBookLength() {
        File file = new File(curBook.getPath());
        return (int) file.length();
    }


    /**
     * 作用：为控件设置适配器
     */


    private void setAdapter() {
        //为viewPager设置适配器
        BookmarkPagerAdapter pagerAdapter = new BookmarkPagerAdapter(getSupportFragmentManager(), fragmentList);
        markPager.setAdapter(pagerAdapter);
    }


    /**
     * 作用，设置监听器
     */


    private void setListener() {
        ibBookmarkBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BookmarkList.this.finish();
            }
        });

    }


}



